package com.org.cys.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.org.cys.controller.base.BaseController;
import com.org.cys.pojo.base.Page;
import com.org.cys.service.system.RoleService;
import com.org.cys.service.system.UserRoleService;
import com.org.cys.service.system.UserService;
import com.org.cys.util.ExportExcel;
import com.org.cys.util.MD5;
import com.org.cys.util.MapUtil;
import com.org.cys.util.PageData;
import com.org.cys.util.StringUtil;  
  

/**
 * 后台用户Controller
 * @author caiyushen
 * */
@Controller  
@RequestMapping("/user")  
public class UserController extends BaseController{  
    
	private static Logger logger = Logger.getLogger(UserController.class);
	
	@Resource(name="userServiceImpl")
    private UserService userService;  
     
	@Resource(name="roleServiceImpl")
	private RoleService roleService;
    
	@Resource(name="userRoleServiceImpl")
	private UserRoleService userRoleService;
	
   /**
    * 去用户列表页面
    * @author caiyushen
    * */
    @RequestMapping(value="/toList",method = RequestMethod.GET)  
    public String toList() throws Exception{  
        return "user/list";  
    }  
	
	
    /**
     * 获取列表信息
     * @param page 分页实体类
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(value="/list",method = RequestMethod.GET)
    public PageData list(Page page){
    	PageData pd = new PageData();
    	try{
    		pd = this.getPageData();
    		page.setPd(pd);
    		logger.info("method list() param: " + page.toString());
    		List<PageData> dataList = userService.dataList(page);
    		pd.put("dataList", dataList);
    		pd.put("total",page.getTotalResult());
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    	}
    	return pd;
    }
    
    /**
     * 新增用户
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public PageData add(@RequestBody PageData pd){
    	logger.info("method add() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		if(!checkUserAccount(pd)){
    			result.put("success", false);
    			result.put("error", "改用户账号已存在");
    			return result;
    		}
    		//密码加密保存
    		pd.put("userPassword",MD5.convertPassword(MapUtil.getString(pd,"userAccount"), MapUtil.getString(pd,"userPassword")));
    		userService.save(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
   
    
    /**
     * 修改用户
     * （无法修改账号、密码）
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT)
    public PageData update(@RequestBody PageData pd){
    	logger.info("method update() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		userService.update(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
    
    /**
     * 修改密码
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(value="/updatePassword",method = RequestMethod.PUT)
    public PageData updatePassword(@RequestBody PageData pd){
    	logger.info("method updatePassword() param: "+pd.toString());
    	PageData result = new PageData();
    	String userPassword = MapUtil.getString(pd,"userPassword").trim();
    	if(!StringUtil.checkObj(userPassword)){
    		result.put("success", false);
    		result.put("error", "用户密码不能为空！");
    		return result;
    	}
    	try{
    		//密码加密保存
    		pd.put("userPassword",MD5.convertPassword(MapUtil.getString(pd,"userAccount"),userPassword));
    		userService.updatePassword(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    		result.put("error", "服务器发生错误！");
    	}
    	return result;
    }
    
    
    /**
     * 检测用户账号唯一性判断
     * @pram pd userAccount
     * @author caiyushen
     * */
    public boolean checkUserAccount(PageData pd){
    	try {
			List<PageData> dataList = userService.getListByAccount(MapUtil.getString(pd,"userAccount"));
			if(StringUtil.checkObj(dataList) && dataList.size()>0){
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return true;
    }
    
    
    /**
     * 删除用户
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE)
    public PageData delete(@RequestBody PageData pd){
    	logger.info("method delete() param: "+pd.toString());
    	PageData result = new PageData();
    	try{
    		userService.delete(pd);
    		result.put("success", true);
    	}catch(Exception e){
    		logger.error(e.toString(),e);
    		result.put("success", false);
    	}
    	return result;
    }
    
    /**
     * 导出Excel数据
     * */
    @RequestMapping(value="/exportExcel",method = RequestMethod.GET)
    public ModelAndView exportExcel(){
    	ModelAndView mv = new ModelAndView();
    	PageData pd = new PageData();
    	pd = this.getPageData();
    	try{
    		Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("用户名"); //1
			titles.add("账号");	//2
			titles.add("密码");	//3
			titles.add("备注");	//4
			dataMap.put("titles", titles);
			List<PageData> varOList = userService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("userName"));	//1
				vpd.put("var2", varOList.get(i).getString("userAccount"));	//2
				vpd.put("var3", varOList.get(i).getString("userPassword"));	//3
				vpd.put("var4", varOList.get(i).getString("userRemark"));	//3
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ExportExcel erv = new ExportExcel();
			mv = new ModelAndView(erv,dataMap);
    	}catch(Exception e){
			logger.error(e.toString(), e);
		}
    	
    	return mv;
    }
    
    /**
     * 批量删除
     * @author caiyushen
     * */
    @ResponseBody
    @RequestMapping(value="/deleteAll",method = RequestMethod.DELETE)
	public PageData deleteAll(@RequestBody PageData pd){
    	logger.info("method deleteAll() param: "+pd.toString());
    	try {
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				userService.deleteAll(ArrayDATA_IDS);
				pd.put("success", true);
			}else{
				pd.put("success", false);
			}
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return pd;
    }
    
    /**
     * 获取角色列表
     * @throws Exception 
     * */
    @ResponseBody
    @RequestMapping(value="/getRoleList",method = RequestMethod.GET)
    public PageData getRoleList() throws Exception{
    	logger.info("method getRoleList()");
    	PageData pd = new PageData();
    	List<PageData> dataList = roleService.listAll(pd);
    	pd.put("dataList", dataList);
    	return pd;
    }
    
    /**
     * 根据用户id获取用户-角色关联数据
     * */
    @ResponseBody
    @RequestMapping(value="/getUserRoleByUserId",method = RequestMethod.GET)
    public PageData getUserRoleByUserId(@RequestParam Long userId){
    	PageData pd = new PageData();
    	List<PageData> dataList = new ArrayList<>();
    	try {
			dataList = userRoleService.getListByUserId(userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	pd.put("dataList", dataList);
    	return pd;
    }
    
    /**
     * 保存用户-角色关联
     * @param pd-userId 用户id
     * @param pd-roleId 角色id
     * */
    @ResponseBody
    @RequestMapping(value="/saveUserRole",method = RequestMethod.POST)
    public PageData saveUserRole(@RequestBody PageData pd) throws Exception{
    	logger.info("method saveUserRole() param: pd->"+pd.toString());
    	List<PageData> dataList = new ArrayList<>();
    	dataList.add(pd);
    	userRoleService.saveBatchByUserId(dataList, MapUtil.getLong(pd,"userId"));
    	return pd;
    }
    
}  